//
//  GetMainPageMessageModel.swift
//  CSYMicroBlockSina
//
//  Created by 姚彦兆 on 15/11/15.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

import UIKit

import AFNetworking

import SVProgressHUD

import SDWebImage

class GetMainPageMessageModel: NSObject {

    //定义一个参数来获取最新的微博
//    var since_id = 0
    
    //定义一个参数来获取旧的微博
//    var max_id = 0
    
    class func loadUserData ( since_id since_id : Int64 , max_id : Int64 , finishedBlock : (array : [CSYMyMicroBlogModel]?) -> ()){
        
        guard let token = GetUserInfoModel().userToken else{
        
            UIView.animateWithDuration(1.25, animations: { () -> Void in
                
                SVProgressHUD.showErrorWithStatus("对不起您暂未登陆", maskType: SVProgressHUDMaskType.Black)
                
                }, completion: { (_) -> Void in
                    
                    SVProgressHUD.dismiss()
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(APPDELEGATESHOULDSWITCHROOTVIEWCONTROLLER, object:nil)
                    
            })
            
            return
            
        }
        
        //用户肯定登陆了-->执行下面的逻辑
        
        var modelArray = [CSYMyMicroBlogModel]()
        
        SVProgressHUD.showWithStatus("正在加载数据", maskType: SVProgressHUDMaskType.Clear)
        
        let urlStr : String = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var parameters : [String : AnyObject] = ["access_token" : token]
        
        //确保正确的情况下来使用获取新微博或旧微博的数据
        
        if since_id > 0 {
            
            parameters["since_id"] = "\(since_id)"
            
            print("------\(since_id)-------\(max_id)")
            
        }else if max_id > 0{
            
            print("上拉加载")
            
            parameters["max_id"] = "\(max_id - 1)"
            
            print("------\(since_id)-------\(max_id)")
            
        }
        
        NetworkTools.shareNetWorkTools.requiredJsonValueToDictionary(AFNSESSION_TYPE.GET, urlStr: urlStr, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
            
                print("HAS ERROR \(error)")
                
                finishedBlock(array: nil)
            
                return
                
            }
            
//            print(result)
            
            if let dataArray = result!["statuses"] as? [[String : AnyObject]] {
                
                for dict in dataArray{
                    
                    let model = CSYMyMicroBlogModel(dict: dict)
                    
                    modelArray.append(model)
                    
                }
                
                GetMainPageMessageModel.cacheImage(modelArray, finishedBlock: finishedBlock)
                
            }

            
        }
        
        
//        let AFN = AFHTTPSessionManager()
//        
//        AFN.GET(urlStr, parameters: parameters, success: { (_, result) -> Void in
//            
//            //字典转模型
//            //            print(result)
//            
//            
//            
//            }) { (_, error) -> Void in
//
//                finishedBlock(array: nil)
//                
//        }
//        
//        
    }
    
    
    private class func cacheImage( dataArray : [CSYMyMicroBlogModel]? , finishedBlock : (array : [CSYMyMicroBlogModel]?) -> ()){
    
        //如果模型数组为空,则返回nil
        if dataArray?.count == 0 {
        
            finishedBlock(array: nil)
            
            return
        
        }
        
        //遍历数组
        for item in dataArray!{
        
            if let urlArray = item.blogPictures{
            
                if urlArray.count != 1{
                    
                    continue
                    
                }
                
                for urlSTR in urlArray{
                //如果为图片数量1 执行操作
                    
//                    let url = urlSTR.absoluteString
                    
                    dispatch_group_enter(group_dispatch)
                    
//                    DownLoadImageTools().downLoadImage(url, finishedBlock: { (image) -> () in
//                        
//                        print("单个图片下载")
//                        
//                        dispatch_group_leave(group_dispatch)
//                        
//                    })
                    
                    SDWebImageManager.sharedManager().downloadImageWithURL(urlSTR, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                        
                        print("单个图片下载")
                        
                        dispatch_group_leave(group_dispatch)
                        
                    })
                    
                }
                
            }
        
        }
        
        dispatch_group_notify(group_dispatch, dispatch_get_main_queue()) { () -> Void in
            
            finishedBlock(array: dataArray)
            
        }

    }
    
    
}
















